package com.ganzi.manager.activiti.service.imp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ganzi.manager.activiti.request.VacationRequest;
import com.ganzi.manager.activiti.vo.StartVacationVo;
import com.ganzi.manager.activiti.entity.WaitAuditVo;
import com.ganzi.manager.activiti.model.BusinessInformation;
import com.ganzi.manager.activiti.model.FormInformation;
import com.ganzi.manager.activiti.service.BusinessformationService;
import com.ganzi.manager.activiti.service.FormformationService;
import com.ganzi.manager.activiti.util.ActivitiUtil;
import com.ganzi.manager.activiti.util.JsonMapUtil;
import com.ganzi.manager.activiti.util.TimeUtil;
import com.ganzi.manager.activiti.vo.*;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.*;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lxd
 * @create 2019/6/28
 * 流程管理类，发起，审批，查看
 */
@Service
public class VacationService {

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private FormService formService;
    @Resource
    private FormformationService formformationService;
    @Resource
    private BusinessformationService businessformationService;
    @Resource
    private ObjectMapper objectMapper;


    /**
     * 获取审批开始表单页面，根据processdefId流程定义id
     */

    public Map<String, Object> getStartPage(String userId, String processdefId) {
        Map<String, Object> result = new HashMap<>();
        //根据流程定义id获取流程图
        BpmnModel bm = repositoryService.getBpmnModel(processdefId);
        Process process = bm.getMainProcess();
        FlowElement firstNode = process.getInitialFlowElement();
        if (firstNode instanceof StartEvent) {
            //重开始节点获取到自定义表单信息（用户自定义的表单信息 目前关联到节点的FormKey上面）
            StartEvent startEvent = (StartEvent) firstNode;
            String formKey = startEvent.getFormKey();
            if (StringUtils.isNotBlank(formKey)) {
                FormInformation tempf = getFormInformationByKey(formKey);
                if (tempf != null) {
                    Map<String, String> data = new HashMap<>();
                    data.put("html",tempf.getParseForm());
                    data.put("htmlJson",tempf.getParseJson());
                    data.put("name",tempf.getName());
                    data.put("processdefId",processdefId);
                    data.put("formKey",formKey);
                    result.put("code", "SUCCESS");
                    result.put("data", data);
                } else {
                    result.put("code", "FAILURE");
                    result.put("msg", "表单Key:" + formKey + "不存在！");
                }
            } else {
                result.put("code", "FAILURE");
                result.put("msg", "开始节点没有绑定表单信息！");
            }
        } else {
            result.put("code", "FAILURE");
            result.put("msg", "流程定义中没有开始节点！");
        }
        return result;
    }

    /**
     * 开始提交流程
     */
    public Object startVac(String UserId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String processdefId = request.getParameter("processId");
            String formKey = request.getParameter("formKey");
            if (StringUtils.isBlank(processdefId)) {
                result.put("code", "FAILURE");
                result.put("msg", "业务流程不存在！");
            } else {
                //获取表单参数
                Enumeration<String> m = request.getParameterNames();
                Map<String, Object> var = new HashMap<>();
                while (m.hasMoreElements()) {
                    String pname = m.nextElement();
                    String va = request.getParameter(pname);
                    System.out.print(pname + ":" + va);
                    //忽略参数  :流程定义Id和表单Key
                    if ("formKey".equals(pname) || "processId".equals(pname)) {
                        continue;
                    }
                    var.put(pname, va);
                }
                //创建业务
                BusinessInformation in = BusinessInformation.builder().assignee(UserId).isInitiator(1)
                        .data(JsonMapUtil.toJsonObj(var).toString()).build();
                boolean temp = businessformationService.insert(in);
                Integer businessId = in.getId();
                if (temp && businessId != null) {
                    //提取出表单中的流程变量
                    Map<String, Object> processVar = getProcessVar(formKey, var);
                    //流程发起前设置发起人，记录在流程历史中
                    identityService.setAuthenticatedUserId(UserId);
                    //开始流程通过act_re_procdef中的id，并设置业务Id
                    ProcessInstance vacationInstance = runtimeService.startProcessInstanceById(processdefId, businessId.toString());
                    runtimeService.setProcessInstanceName(vacationInstance.getId(), "流程实例名称：" + UserId);
                    //查询当前任务
                    Task currentTask = taskService.createTaskQuery().processInstanceId(vacationInstance.getId()).singleResult();
                    //领取任务
                    taskService.claim(currentTask.getId(), UserId);
                    //发起人完成任务
                    taskService.complete(currentTask.getId(), processVar);
                    //把当前流程实例Id更新到业务数据,方便后续审批业务查询发起人提交的数据（-------？）
                    in.setProcessId(vacationInstance.getId());
                    in.setFormKey(formKey);
                    businessformationService.updateById(in);
                    result.put("code", "SUCCESS");
                }
            }
            result.put("code", "FAILURE");
            result.put("msg", "业务信息创建失败！");
        } catch (Exception e) {
            result.put("code", "FAILURE");
            result.put("msg", "业务信息创建失败！");

        }
        return result;
    }


    /**
     * 开始流程,自定义审批人
     */
    public Object startVacByAssignee(String userName, VacationRequest vac) {

//        //流程发起前设置发起人，记录在流程历史中
//        identityService.setAuthenticatedUserId(userName);
//        // 开始流程
//        ProcessInstance vacationInstance = runtimeService.startProcessInstanceByKey(vac.getProcessKey());
//        // 查询当前任务
//        Task currentTask = taskService.createTaskQuery().processInstanceId(vacationInstance.getId()).singleResult();
//        // 申明任务
//        taskService.claim(currentTask.getId(), userName);
//
//        Map<String, Object> vars = new HashMap<>(10);
//        vars.put("manage", vac.getManage());
//        vars.put("dir", vac.getDir());
//        vars.put("applyUser", userName);
//        vars.put("days", vac.getDays());
//        vars.put("reason", vac.getReason());
//        System.out.println("oooo:"+vac.getReason());
//        taskService.complete(currentTask.getId(), vars);

        return true;
    }

    /**
     * 显示所有发布的流程（可以设置显示最新版本）
     */
    public Object getProcess() {
        Map<String, Object> result = new HashMap<>();
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                .orderByProcessDefinitionVersion().asc().list();
        List<ProcessAllVo> processAllList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (ProcessDefinition processDefinition : list) {
                ProcessAllVo pro = new ProcessAllVo();
                pro.setName(processDefinition.getName());
                pro.setKey(processDefinition.getId());
                pro.setId(processDefinition.getDeploymentId());
                pro.setDec(processDefinition.getDescription());
                processAllList.add(pro);
            }
        }
        result.put("code", "SUCCESS");
        result.put("data", processAllList);
        return result;
    }

    /**
     * 我正在申请的
     */
    public Object myVac(String userId) {
        //按发起人查询 发起的申请
        Map<String, Object> result = new HashMap<>();
        List<ProcessInstance> instanceList = runtimeService.createProcessInstanceQuery().startedBy(userId).list();
        List<StartVacationVo> vacList = new ArrayList<>();
        for (ProcessInstance instance : instanceList) {
            vacList.add(StartVacationVo.builder().name(instance.getProcessDefinitionName())
                    .state(instance.isEnded() ? "申请结束" : "等待审批")
                    .startTime(instance.getStartTime()).build());
        }
        result.put("code", "SUCCESS");
        result.put("data", vacList);
        return result;
    }

    /**
     * 等待我审批的
     */
    public Object myAudit(String userId) {
        Map<String, Object> result = new HashMap<>();
        List<Task> taskList = taskService.createTaskQuery().taskCandidateOrAssigned(userId)
                .orderByTaskCreateTime().desc().list();
        List<WaitAuditVo> vacTaskList = new ArrayList<>();
        for (Task task : taskList) {
            String instanceId = task.getProcessInstanceId();
            ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
            WaitAuditVo audit = WaitAuditVo.builder()
                    .taskId(task.getId())
                    .taskName(task.getName())
                    .processName(instance.getProcessDefinitionName())
                    .tStartTime(task.getCreateTime())
                    .pStartTime(instance.getStartTime())
                    .UserId(instance.getStartUserId()).build();
            System.out.println("----流程开始时间:" + instance.getStartTime());
            vacTaskList.add(audit);
        }
        result.put("code", "SUCCESS");
        result.put("data", vacTaskList);
        return result;
    }

    /**
     * 进入审批详情页面
     */
    public Map<String, Object> AuditInformation(String userId, String taskId) {
        Map<String, Object> result = new HashMap<>();
        try {
            TaskFormData formData = formService.getTaskFormData(taskId);
            CustomFormVo cv = null;
            //根据任务获取自定义表单
            String NowformKey = formData.getFormKey();
            //获取当前任务
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            String processDefinitionId = task.getProcessDefinitionId();
            //获取当前节点
            ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            //获取开始节点的表单(也就是发起人表单)
            String initiateFormKey = getFormKeyByStartNode(processDefinitionId);
            if (StringUtils.isBlank(initiateFormKey)) {
                //如果开始节点没有表单就从发起人节点获取表单
                initiateFormKey = getFormKeyByStartUserId(task.getProcessInstanceId(), instance.getStartUserId());
            }
            if (StringUtils.isNotBlank(initiateFormKey)) {
                //当前任务表单
                FormInformation nowFin = getFormInformationByKey(NowformKey);
                //如果当前任务没有自定义表单，就返回默认表单(默认表单就是一个审核备注)
                if (nowFin == null) {
                    nowFin = getFormInformationByKey(JsonMapUtil.DE_NOTE_FORMKEY);
                }
                //发起人表单
                FormInformation initiateFin = getFormInformationByKey(initiateFormKey);
                if (initiateFin != null) {
                    //获取流程实例中的业务key(这个key是发起人的业务key)
                    String businessKey = instance.getBusinessKey();
                    if (StringUtils.isNotBlank(businessKey)) {
                        //获取发起人的业务信息（显示给审批人看，后面可以做成显示之前审批人提交的信息，根据当前节点查询之前节点的审批人业务信息）
                        BusinessInformation business = getBusinessInformationByid(businessKey);
                        if (business != null) {
                            cv = CustomFormVo.builder()
                                    .nowHtml(nowFin != null ? nowFin.getParseForm() : "")
                                    .nowJson(nowFin != null ? nowFin.getParseJson() : "")
                                    .initiateHtml(initiateFin.getParseForm())
                                    .initiateJson(initiateFin.getParseJson())
                                    .initiateData(JsonMapUtil.toMapObj(business.getData()))
                                    .processId(instance.getId())
                                    .taskId(task.getId())
                                    .formKey(initiateFin.getFormKey())
                                    .build();
                            result.put("code", "SUCCESS");
                            result.put("data", cv);
                            return result;
                        }
                    }
                    result.put("code", "FAILURE");
                    result.put("msg", "流程中没有对应的业务数据！");
                    return result;
                }
            }
            result.put("code", "FAILURE");
            result.put("msg", "流程中没有对应的表单！");
        } catch (Exception e) {
            result.put("code", "FAILURE");
            result.put("msg", "系统异常！");
        }
        return result;
    }

    /**
     * 提交审核操作
     * 硬编码流程变量：（可以在流程中使用）
     * 同意和拒绝变量  zmdActivitiAllow  1表示同意   0表示拒绝
     * 执行人变量 zmdActivitiTaskUser
     */
    public Object passAudit(String userId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            Enumeration<String> m = request.getParameterNames();
            Map<String, Object> var = new HashMap<>();
            while (m.hasMoreElements()) {
                String pname = m.nextElement();
                String va = request.getParameter(pname);
                System.out.print(pname + ":" + va);
                var.put(pname, va);
            }
            //流程实例id和任务id
            String processId = request.getParameter("processId");
            String taskId = request.getParameter("taskId");
            String formKey = request.getParameter("formKey");
            //审批结果
            String zmdActivitiAllow = request.getParameter(JsonMapUtil.ALLOW);
            //保存审批业务信息（如果每个节点有对应的表单，那么表单数据先从当前业务数据匹配，匹配不上在去发起人业务数据中去 匹配）
            BusinessInformation in = BusinessInformation.builder().assignee(userId)
                    .processId(processId).taskId(taskId)
                    .data(JsonMapUtil.toJsonObj(var).toString()).build();
            boolean temp = businessformationService.insert(in);
            if (temp) {
                //取出表单中的流程变量
                Map<String, Object> processVars = getProcessVar(formKey, var);
                //传入审批结果审批结果（目的是为了再画流程图的时候作为条件）
                processVars.put(JsonMapUtil.ALLOW, zmdActivitiAllow);
                //传入审批人---》????这儿没有考虑会签的时候  多个人同时审批的情况---?????????????/
                processVars.put(JsonMapUtil.TASK_USER, userId);
                //获取流程当前节点
                Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
                UserTask nowFlow = getOneFlowElement(task.getProcessDefinitionId(), task.getTaskDefinitionKey());
                //获取出口连线
                List<SequenceFlow> out = null;
                if (nowFlow != null) {
                    out = nowFlow.getOutgoingFlows();
                }
                //领取任务
                taskService.claim(taskId, userId);
                //完成任务
                taskService.complete(taskId, processVars);
                //如果只有一个出口
                if (out != null && out.size() <= 1) {
                    SequenceFlow first = out.get(0);
                    FlowElement element = first.getTargetFlowElement();
                    //如果下一级节点不是网关，并且审批人拒绝了，就直接结束流程；
                    if (!(element instanceof Gateway) && "0".equals(zmdActivitiAllow)) {
                        stopProcess(processId);
                    }
                }
                result.put("code", "SUCCESS");
            } else {
                result.put("code", "FAILURE");
                result.put("msg", "流程中没有对应的表单！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "FAILURE");
            result.put("msg", "系统异常！");
        }
        return result;
    }


    /**
     * 我申请完成的
     */
    public Object myVacRecord(String userId) {
        Map<String, Object> result = new HashMap<>();
        List<HistoricProcessInstance> hisProInstance = historyService.createHistoricProcessInstanceQuery()
                .startedBy(userId).finished()
                .orderByProcessInstanceEndTime().desc().list();

        List<EndAuditVo> vacList = new ArrayList<>();
        for (HistoricProcessInstance hisInstance : hisProInstance) {
            //获取参数列表
            List<HistoricVariableInstance> varInstanceList = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(hisInstance.getId()).list();
            EndAuditVo endAudit = EndAuditVo.builder().processName(hisInstance.getProcessDefinitionName())
                    .pStartTime(hisInstance.getStartTime())
                    .procesId(hisInstance.getId())
                    .pEndTime(hisInstance.getEndTime()).build();
            //设置审批结果和执行人
            varInstanceList.stream().forEach(item -> {
                if (JsonMapUtil.ALLOW.equals(item.getVariableName())) {
                    endAudit.setState("0".equals(item.getValue()) ? "拒绝" : "同意");
                }
                if (JsonMapUtil.TASK_USER.equals(item.getVariableName())) {
                    endAudit.setUserId((String) item.getValue());
                }
            });
            vacList.add(endAudit);
        }
        result.put("code", "SUCCESS");
        result.put("data", vacList);
        return result;
    }

    /**
     * 申请完成的详情
     */
    public Map<String, Object> initiateComplete(String processId) {
        Map<String, Object> result = new HashMap<>();
        HistoricProcessInstance hisProInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processId).singleResult();
        //查询流程的所有Activity
        List<HistoricActivityInstance> hisActList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processId)
                .orderByHistoricActivityInstanceEndTime().asc().list();
        //获取开始节点的表单（默认就是发起人的表单）
        String initiateFormKey = getFormKeyByStartNode(hisProInstance.getProcessDefinitionId());
        if (StringUtils.isBlank(initiateFormKey)) {
            //如果开始节点没有表单就从发起人节点获取表单
            initiateFormKey = getFormKeyByStartUserId(processId, hisProInstance.getStartUserId());
        }
        //获取发起人提交的业务数据
        String businessKey = hisProInstance.getBusinessKey();
        if (StringUtils.isNotBlank(initiateFormKey) && StringUtils.isNotBlank(businessKey)) {
            //获取发起人的表单信息和业务数据
            FormInformation initiateForm = getFormInformationByKey(initiateFormKey);
            BusinessInformation business = getBusinessInformationByid(businessKey);
            if (initiateForm != null && business != null) {
                InitiateCompleteVo vo = InitiateCompleteVo.builder().processId(processId)
                        .initiateHtml(initiateForm.getParseForm())
                        .initiateJson(initiateForm.getParseJson())
                        .initiateData(JsonMapUtil.toMapObj(business.getData()))
                        .build();
                List<Map<String, Object>> auditInformation = new ArrayList<>();
                //获取审批人的信息
                hisActList.stream().filter(h -> "userTask".equals(h.getActivityType()) && !h.getAssignee().equals(hisProInstance.getStartUserId())).forEach(item -> {
                    System.out.print("---::::" + item.getAssignee());

                    Map<String, Object> temMap = new HashMap<>();
                    temMap.put("assignee", item.getAssignee());
                    //获取节点：item.getActivityId() == task_def_key，相当于流程图中的id
                    UserTask task = getOneFlowElement(item.getProcessDefinitionId(), item.getActivityId());
                    String tempKey = task.getFormKey();
                    if (StringUtils.isBlank(tempKey)) {
                        //如果当前节点没有表单就获取默认表单
                        tempKey = JsonMapUtil.DE_NOTE_FORMKEY;
                    }
                    //获取表单信息
                    FormInformation tempForm = getFormInformationByKey(tempKey);
                    if (tempForm != null) {
                        //获取业务数据
                        BusinessInformation tempbusin = getBusinessInformation(item.getTaskId(), item.getAssignee());
                        temMap.put("html", tempForm.getParseForm());
                        temMap.put("json", tempForm.getParseJson());
                        temMap.put("data", tempbusin != null ? JsonMapUtil.toMapObj(tempbusin.getData()) : "");
                    }
                    temMap.put("time", TimeUtil.formateDate(item.getEndTime()));
                    temMap.put("taskId", item.getTaskId());
                    auditInformation.add(temMap);
                });
                vo.setAuditInformation(auditInformation);
                result.put("code", "FAILURE");
                result.put("data", vo);
            }
        }
        result.put("code", "FAILURE");
        result.put("msg", "流程中没有对应的表单或数据！");
        return result;
    }

    /**
     * 我完成审批的
     */
    public Object myAuditRecord(String userId) {
        Map<String, Object> result = new HashMap<>();
        List<HistoricProcessInstance> hisProInstance = historyService.createHistoricProcessInstanceQuery()
                .involvedUser(userId).finished()
                .orderByProcessInstanceEndTime().desc().list();
        List<MyAuditVo> auditList = new ArrayList<>();
        String uId;
        for (HistoricProcessInstance hisInstance : hisProInstance) {
            //发起人id
            uId = hisInstance.getStartUserId();
            //屏蔽发起人是当前用户
            if (uId.equals(userId)) {
                continue;
            }
            //查询出已经结束的流程中包含当前用户为审批人的流程
            List<HistoricActivityInstance> hisActList = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(hisInstance.getId())
                    .taskAssignee(userId)
                    .orderByHistoricActivityInstanceEndTime().desc().list();
            boolean isMyAudit = false;
            HistoricActivityInstance myAct = null;
            //查询出当前用户具体的Task
            for (HistoricActivityInstance taskInstance : hisActList) {
                if (taskInstance.getAssignee().equals(userId)) {
                    isMyAudit = true;
                    myAct = taskInstance;
                    break;
                }
            }
            if (!isMyAudit) {
                continue;
            }
            BusinessInformation bus = getBusinessInformation(myAct.getTaskId(), userId);
            int zmdActivitiAllow = 1;
            if (bus != null) {
                //从当前用户的业务参数中 获取审核状态
                Map<String, Object> var = JsonMapUtil.toMapObj(bus.getData());
                boolean m = var.containsKey(JsonMapUtil.ALLOW);
                if (m) {
                    zmdActivitiAllow = Integer.parseInt(var.get(JsonMapUtil.ALLOW).toString());
                }
            }
            MyAuditVo audit = MyAuditVo.builder()
                    .startUserId(uId)
                    .endUserId(userId)
                    .audirState(zmdActivitiAllow == 1 ? "通过" : "拒绝")
                    .pAuditTime(myAct.getEndTime())
                    .processName(hisInstance.getProcessDefinitionName())
                    .pStartTime(hisInstance.getStartTime())
                    .pstate(hisInstance.getEndTime() != null ? "完成审批" : "审批中")
                    .build();
            //如果流程结束，查询最后状态参数
            if (hisInstance.getEndTime() != null) {
                //获取流程参数，获取最后流程的执行人和状态（这个其实也可以从业务部中查询-----？）
                List<HistoricVariableInstance> varInstanceList = historyService.createHistoricVariableInstanceQuery()
                        .processInstanceId(hisInstance.getId()).list();
                String allowString = ActivitiUtil.getVars(JsonMapUtil.ALLOW, varInstanceList);
                int allow = allowString != null ? Integer.parseInt(allowString) : 0;
                String user = ActivitiUtil.getVars(JsonMapUtil.TASK_USER, varInstanceList);
                audit.setPaudirState(allow == 1 ? "通过" : "拒绝");
                audit.setPendUserId(user);
            }
            auditList.add(audit);
        }
        result.put("code", "SUCCESS");
        result.put("data", auditList);
        return result;
    }

    /**
     * 获取表单中的 流程变量
     */
    private Map<String, Object> getProcessVar(String formKey, Map<String, Object> var) throws Exception {
        if (StringUtils.isNotBlank(formKey)) {
            Map<String, Object> map = new HashMap<>();
            FormInformation tempf = getFormInformationByKey(formKey);
            if (tempf != null && var != null) {
                //获取表单中需要传递到流程中的变量（目的是用来在画流程图的时候作为网关的判断条件）
                String param = tempf.getProcessParam();
                Set<String> keyPara = JsonMapUtil.toMapObj(param).keySet();
                Iterator<String> it = keyPara.iterator();
                while (it.hasNext()) {
                    String str = it.next();
                    String value = (String) var.get(str);
                    //如果表单存在这个值就存在流程变量中
                    if (StringUtils.isNotBlank(value)) {
                        map.put(str, value);
                    }
                }
                return map;
            }
        }
        return var;
    }

    /**
     * 通过formKey获取表单数据
     */
    public FormInformation getFormInformationByKey(String formKey) {
        if (StringUtils.isNotBlank(formKey)) {
            Map<String, Object> map = new HashMap<>();
            map.put("form_key", formKey);
            List<FormInformation> form = formformationService.selectByMap(map);
            if (form != null && form.size() > 0) {
                return form.get(0);
            }
        }
        return null;
    }

    /**
     * 通过businessKey获取业务数据
     */
    public BusinessInformation getBusinessInformationByid(String businessKey) {
        BusinessInformation business = businessformationService.selectById(businessKey);
        return business;
    }

    /**
     * 通过task_id,assignee获取业务数据
     */
    public BusinessInformation getBusinessInformation(String taskId, String assignee) {
        BusinessInformation business = null;
        if (StringUtils.isNotBlank(taskId) && StringUtils.isNotBlank(assignee)) {
            Map<String, Object> var = new HashMap<>();
            var.put("task_id", taskId);
            var.put("assignee", assignee);
            List<BusinessInformation> businessList = businessformationService.selectByMap(var);
            if (businessList != null && businessList.size() > 0) {
                business = businessList.get(0);
            }
        }
        return business;
    }

    /**
     * 通过流程定义id获取开始节点的表单值
     */
    public String getFormKeyByStartNode(String proId) {
        String result = null;
        BpmnModel bm = repositoryService.getBpmnModel(proId);
        Process process = bm.getMainProcess();
        FlowElement firstNode = process.getInitialFlowElement();
        if (firstNode instanceof StartEvent) {
            //重开始节点获取到自定义表单信息
            StartEvent startEvent = (StartEvent) firstNode;
            result = startEvent.getFormKey();
        }
        return result;
    }


    /**
     * 获取发起人的表单信息；
     * processId: 流程实例id
     * startUserId：发起人id
     */
    public String getFormKeyByStartUserId(String processId, String startUserId) {
        String result = null;
        if (StringUtils.isNotBlank(processId) && StringUtils.isNotBlank(startUserId)) {
            //查询流程的所有Activity
            List<HistoricActivityInstance> hisActList = historyService.createHistoricActivityInstanceQuery()
                    .processInstanceId(processId)
                    .orderByHistoricActivityInstanceStartTime().asc().list();
            Optional<HistoricActivityInstance> hisAct = hisActList.stream().filter(h -> h.getAssignee().equals(startUserId)).findFirst();
            if (hisAct.isPresent()) {
                HistoricActivityInstance act = hisAct.get();
                //如果是用户节点
                if ("userTask".equals(act.getActivityType())) {
                    //获取到任务节点的key(流程图中的id)
                    String taskKey = act.getActivityId();
                    UserTask tempTask = getOneFlowElement(act.getProcessDefinitionId(), taskKey);
                    if (tempTask != null) {
                        result = tempTask.getFormKey();
                    }
                }
            }
        }
        return result;
    }

    /**
     * 终止流程 根据流程实例id
     */
    public void stopProcess(String processId) {
        ProcessInstance ins = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (ins != null) {
            runtimeService.deleteProcessInstance(processId, "结束");
        }
    }

    /**
     * 获取所以的节点 通过流程实例id
     */
    public Collection<FlowElement> getAllFlowElement(String processDefId) {
        BpmnModel bm = repositoryService.getBpmnModel(processDefId);
        Process process = bm.getMainProcess();
        Collection<FlowElement> allElement = process.getFlowElements();
        return allElement;
    }

    /**
     * 获取节点：通过流程的定义id:processDefId  和任务的定义key：taskKey
     */
    public UserTask getOneFlowElement(String processDefId, String taskKey) {
        UserTask u = null;
        Collection<FlowElement> allElement = getAllFlowElement(processDefId);
        System.out.println("---taskKey:" + taskKey);
        Optional<FlowElement> element = allElement.stream().filter(P -> taskKey.equals(P.getId())).findFirst();
        if (element.isPresent()) {
            FlowElement flow = element.get();
            if (flow instanceof UserTask) {
                u = (UserTask) flow;
            }
        }
        return u;
    }

}
